<template>
	<view>
		<view v-if="value.style == 1 || value.style == 2" class="goods-list" :class="value.style == 1 ? 'single-column' : 'double-column' "
		 :data-theme="themeStyle" :style="{ backgroundColor: value.backgroundColor, marginTop: value.marginTop * 2 + 'rpx' }">
			<view class="goods-item" v-for="(item, index) in goodsList" :key="index" @click="toDetail(item)">
				<view class="goods-img">
					<image :src="goodsImg(item.goods_image)" mode="widthFix" @error="imgError(index)"></image>
					<view class="color-base-bg goods-tag" v-if="value.goodsTag == 'default' && goodsTag(item) != '' ">{{ goodsTag(item) }}</view>
					<view class="goods-tag-img" v-if="value.goodsTag == 'diy'">
						<image :src="$util.img(value.tagImg.imageUrl)" mode=""></image>
					</view>
				</view>
				<view class="info-wrap">
					<view class="name-wrap">
						<view class="goods-name">{{ item.goods_name }}</view>
					</view>
					<view class="pro-info">
						<view class="delete-price font-size-activity-tag color-tip">
							<block>
								<text class="unit">{{ $lang('common.currencySymbol') }}</text>{{ item.market_price > 0 ? item.market_price : item.price }}
							</block>
						</view>
						<view class="sale font-size-activity-tag color-tip">已售{{ item.sale_num }}{{ item.unit ? item.unit : "件" }}</view>
					</view>
					<view class="lineheight-clear">
						<view class="discount-price">
							<text class="unit color-base-text font-size-tag">{{ $lang('common.currencySymbol') }}</text>
							<text class="price color-base-text font-size-toolbar">{{ showPrice(item) }}</text>
						</view>
						<view class="member-price-tag" v-if="item.member_price && item.member_price == showPrice(item)">
							<image :src="$util.img('upload/uniapp/index/VIP.png')" mode="widthFix"></image>
						</view>
						<view class="member-price-tag" v-else-if="item.promotion_type == 1">
							<image :src="$util.img('upload/uniapp/index/discount.png')" mode="widthFix"></image>
						</view>
					</view>
				</view>
			</view>
		</view>

		<view v-if="value.style == 3" class="goods-list goods-list-3 single-column" :data-theme="themeStyle" :style="{ backgroundColor: value.backgroundColor, marginTop: value.marginTop * 2 + 'rpx' }">
			<view class="goods-item" v-for="(item, index) in goodsList" :key="index" @click="toDetail(item)">
				<view class="goods-img">
					<image :src="goodsImg(item.goods_image)" mode="widthFix" @error="imgError(index)"></image>
					<!-- <view class="color-base-bg goods-tag" v-if="value.goodsTag == 'default' && goodsTag(item) != '' ">{{ goodsTag(item) }}</view> -->
					<view class="goods-tag-img" v-if="value.goodsTag == 'diy'">
						<image :src="$util.img(value.tagImg.imageUrl)" mode=""></image>
					</view>
				</view>
				<view class="info-wrap">
					<view class="name-wrap">
						<view class="goods-name">{{ item.goods_name }}</view>
						<view class="goods-label" v-if="goodsTag(item) != ''">{{ goodsTag(item) }}</view>
						<view class="goods-sale">
							<text class="color-tip">累积 {{ item.sale_num }} 份</text>
							<text class="split"></text>
							<text class="color-base-text" v-if="item.stock > 30">剩余 {{item.stock}} 份</text>
							<text class="color-base-text" v-else>仅剩 {{item.stock}} 份</text>
						</view>
					</view>

					<view class="">
						<view class="lineheight-clear">
							<view class="member-price-tag member-price-tag-vip-1" v-if="item.member_price && item.member_price == showPrice(item)">
								<image :src="$util.img('upload/uniapp/index/vip_1.png')" mode="widthFix"></image>
								<text>会员价</text>
							</view>
							<view class="member-price-tag member-price-tag-vip-2" v-else-if="item.promotion_type == 1">
								<image :src="$util.img('upload/uniapp/index/vip_2.png')" mode="widthFix"></image>
								<text>折扣价</text>
							</view>
							<view class="discount-price">
								<text class="unit font-size-tag">{{ $lang('common.currencySymbol') }}</text>
								<text class="price fs38">{{ showPrice(item).split('.')[0] }} </text><text class="font-size-toolbar">.{{ showPrice(item).split('.')[1] }}</text>
							</view>
						</view>

						<view class="pro-info">
							<view class="delete-price color-tip">
								<block>
									<text class="unit">{{ $lang('common.currencySymbol') }}</text>{{ item.market_price > 0 ? item.market_price : item.price }}
								</block>
							</view>
						</view>
					</view>


					<view class="careBox" v-if="item.goods_spec_format">
						<view class="careBox-con">
							<button class="info-btn color-base-bg" @click.stop="getGoodsSkuDetail(item.sku_id)">选规格</button>
							<view v-if="item.num" class="tag-num">{{item.num}}</view>
						</view>
					</view>

					<view class="careBox" v-if="!item.goods_spec_format">
						<button v-if="item.num <= 0 || !token" class="info-btn color-base-bg" @click.stop="cartNumChange('add', item)">加入购物车</button>
						<text v-if="item.num > 0" class="iconfont iconjianshao color-base-text" @click.stop="cartNumChange('minus', item)"></text>
						<input v-if="item.num > 0" :value="item.num" readonly disabled="disabled" unselectable="on" />
						<text v-if="item.num > 0" class="iconfont iconadd-fill color-base-text" @click.stop="cartNumChange('add', item)"></text>
					</view>
				</view>
			</view>
		</view>

		<ns-login ref="login"></ns-login>
		<ns-goods-sku-category @getCartData="getCartData" ref="goodSkuNew" @refresh="refreshGoodsSkuDetail"></ns-goods-sku-category>
	</view>
</template>

<script>
	import globalConfig from '@/common/js/golbalConfig.js';
	import nsGoodsSkuCategory from '@/components/ns-goods-sku/ns-goods-sku-category.vue';
	import nsLogin from '@/components/ns-login/ns-login.vue';

	export default {
		name: 'diy-goods-list',
		props: {
			value: {
				type: Object,
				default: () => {
					return {};
				}
			}
		},
		components: {
			nsGoodsSkuCategory,
			nsLogin
		},
		computed: {
			globalRefresh() {
				return this.$store.state.globalRefresh;
			},
			tokenStore() {
				this.token = this.$store.state.tokenStore;
				return this.$store.state.tokenStore;
			}
		},
		watch: {
			globalRefresh: function(nval, oval) {
				console.log(nval,oval)
				if(nval == 1){
					this.getGoodsList();
				} 
			},
			tokenStore() {
				this.getGoodsList();
			}
		},
		data() {
			return {
				goodsList: [],
				cartList: [],

				goodsSkuDetail: {},
				cartFlag: false,
				token: ''
			};
		},
		mixins: [globalConfig],
		created() {
			this.getGoodsList();
			this.token = uni.getStorageSync('token') ? uni.getStorageSync('token') : '';
			var that = this;
			uni.$on('getgoodslist',function(data){
				that.getGoodsList();
			})
		},
		methods: {
			getGoodsList() {
				
				var data = {
					page: 1,
					page_size: this.value.goodsCount
				};
				if (this.value.sources == 'category') {
					data.category_id = this.value.categoryId;
					data.category_level = 1;
				} else if (this.value.sources == 'diy') {
					data.goods_id_arr = this.value.goodsId.toString();
				}
				this.$api.sendRequest({
					url: '/api/goodssku/page',
					data: data,
					success: res => {
						if (res.code == 0 && res.data) {
							let data = res.data;
							this.goodsList = data.list;
							this.getCartData();
						}
					}
				});
			},
			getCartData() {
				if (!uni.getStorageSync('token')) {
					for (let goods_index in this.goodsList) {
						let goods_item = this.goodsList[goods_index];
						goods_item.num = 0;
					}
					this.$forceUpdate();
					this.$emit('netFinish', true);
					return;
				}
				
				this.$api.sendRequest({
					url: '/api/cart/lists',
					success: res => {
						if (res.code >= 0) {
							this.cartList = res.data;

							for (let goods_index in this.goodsList) {
								let goods_item = this.goodsList[goods_index],
									sku_id = goods_item.sku_id,
									goods_id = goods_item.goods_id,
									num = 0,
									cart_id = '';

								for (let cart_index in this.cartList) {
									let cart_item = this.cartList[cart_index];
									if (goods_id == cart_item.goods_id  && cart_item.activity_type == '') {
										num += cart_item.num;
										cart_id = cart_item.cart_id;
									}
								}
								goods_item.num = num;
								goods_item.cart_id = cart_id;

								if (typeof goods_item.num === 'undefined' || goods_item.num === null) {
									goods_item.num = 0;
								}
							}
							this.$forceUpdate();
							this.$store.commit('setGlobalRefresh', '0');
						}
					}
				});
			},
			toDetail(e) {
				this.$util.redirectTo('/pages/goods/detail/detail', {
					sku_id: e.sku_id
				});
			},
			goodsImg(imgStr) {
				let imgs = imgStr.split(',');
				return imgs[0] ? this.$util.img(imgs[0], {
					size: 'MID'
				}) : this.$util.getDefaultImage().default_goods_img;
			},
			imgError(index) {
				this.goodsList[index].goods_image = this.$util.getDefaultImage().default_goods_img;
			},
			showPrice(data) {
				let price = data.discount_price;
				if (data.member_price && parseFloat(data.member_price) < parseFloat(price)) price = data.member_price;
				return price;
			},
			goodsTag(data) {
				switch (data.recommend_way) {
					case 1:
						return '好货上新';
						break;
					case 2:
						return '精品优选';
						break;
					case 3:
						return '每日推荐';
						break;
					default:
						return '';
				}
			},


			//获取购物车数量
			getCartCount() {
				this.$store.dispatch('getCartNumber').then((e) => {
					this.cartCount = e;
				})
			},
			// 刷新商品sku详情数据
			refreshGoodsSkuDetail(goodsSkuDetail) {
				Object.assign(this.goodsSkuDetail, goodsSkuDetail);
			},
			async getGoodsSkuDetail(skuId) {
				if (!uni.getStorageSync('token')) {
					this.$refs.login.open(this.currentRoute);
					return;
				}

				let res = await this.$api.sendRequest({
					url: '/api/goodssku/getInfoForCategory',
					async: false,
					data: {
						sku_id: skuId,
					}
				});

				let data = res.data;
				if (data) {
					this.goodsSkuDetail = data;

					if (this.skuId == 0) this.skuId = this.goodsSkuDetail.sku_id;

					this.goodsSkuDetail.unit = this.goodsSkuDetail.unit || "件";

					this.goodsSkuDetail.show_price = this.goodsSkuDetail.discount_price;

					// 当前商品SKU规格
					if (this.goodsSkuDetail.sku_spec_format) this.goodsSkuDetail.sku_spec_format = JSON.parse(this.goodsSkuDetail.sku_spec_format);

					// 商品SKU格式
					if (this.goodsSkuDetail.goods_spec_format) this.goodsSkuDetail.goods_spec_format = JSON.parse(this.goodsSkuDetail
						.goods_spec_format);

					this.$refs.goodSkuNew.show("join_cart", this.goodsSkuDetail, () => {
						this.getCartCount();
					});
				} else {
					this.$util.redirectTo('/pages/index/index/index', {}, 'reLaunch');
				}
			},
			// 变更购物车数量
			cartNumChange(type, goods) {
				if (!uni.getStorageSync('token')) {
					this.$refs.login.open('/pages/goods/category/category');
					return;
				}

				let cartData = {
						num: 1,
						cart_id: goods.cart_id,
						sku_id: goods.sku_id
					},
					cartUrl = "", //类型 add--新增商品  edit--修改商品数量  delete--删除商品
					actionType,
					maxBuy = goods.max_buy,
					stock = maxBuy > 0 ? (maxBuy - goods.purchased_num) : goods.stock;

				var minBuy = 1;
				if (goods.min_buy > 1) minBuy = goods.min_buy;
				cartData.num = minBuy; // 最少购买量

				goods.unit = goods.unit || "件";

				if (type == 'add') {

					// 检测是否第一次加入购物车
					if (goods.cart_id) {
						actionType = "edit";
						cartUrl = '/api/cart/edit';
					} else {
						actionType = "add";
						cartUrl = '/api/cart/add';
					}
					if (stock == 0) {
						this.$util.showToast({
							title: '库存不足'
						});
						return;
					} else if (goods.cart_id && goods.num < stock) {
						cartData.num = ++goods.num;
					} else {
						if (maxBuy > 0 && (goods.purchased_num + goods_item.num) >= maxBuy) {
							this.$util.showToast({
								title: '该商品每人限购' + maxBuy + goods.unit + '，您已购买了' + goods.purchased_num + goods.unit
							});
							return;
						}

						if (maxBuy > 0 && goods.num > 0 && goods.num + cartData.num > maxBuy) {
							var diff = maxBuy - goods.num;
							if (diff > 0) {
								this.$util.showToast({
									title: '该商品每人限购' +
										maxBuy +
										goods.unit +
										'，购物车已加入了' +
										goods.num +
										goods.unit +
										'，还能购买' +
										diff +
										goods.unit
								});
							} else {
								this.$util.showToast({
									title: '该商品每人限购' + maxBuy + goods.unit
								});
							}
							return;
						}
					}

				} else if (type == 'minus') {
					cartData.num = goods.num - 1 ? goods.num - 1 : 0;
					cartUrl = cartData.num > 0 ? '/api/cart/edit' : '/api/cart/delete';
					actionType = cartData.num > 0 ? 'edit' : 'delete';
				}

				if (this.cartFlag) return false;
				this.cartFlag = true;

				this.shopDataChange(cartData);

				this.$api.sendRequest({
					url: cartUrl,
					data: cartData,
					success: res => {
						if (res.code >= 0) {
							if (res.data > 0) {
								this.$store.dispatch('getCartNumber');
								this.$store.dispatch('getCartPrice');
								this.$store.dispatch('getCartIds');
								if (actionType == "edit") {
									this.cartFlag = false;
									return false;
								}
								cartData.cart_id = actionType == "add" ? res.data : '';
								if (actionType == 'add') {
									this.$util.showToast({
										title: '加入购物车成功'
									});
								}
							} else {
								cartData.num = goods.num;
								this.$util.showToast({
									title: res.message
								});
							}
							this.shopDataChange(cartData);
						}

						this.cartFlag = false;
					}
				});

			},
			shopDataChange(data) {
				if (this.value.level != 3) {
					for (var i = 0; i < this.goodsList.length; i++) {
						var item = this.goodsList[i];
						if (data.sku_id == item.sku_id) {
							item.num = data.num;
							item.cart_id = data.cart_id;
						}
					}
				} else {
					var categoryList = this.cateList[this.oneIndex].child_list[this.twoIndex].child_list;
					for (var i = 0; i < categoryList.length; i++) {
						if (this.threeIndex.indexOf(i) != -1) {
							for (var k = 0; k < categoryList[i].goods_list.length; k++) {
								if (data.sku_id == categoryList[i].goods_list[k].sku_id) {
									categoryList[i].goods_list[k].num = data.num;
									categoryList[i].goods_list[k].cart_id = data.cart_id;
								}
							}
						}
					}
				}
				this.$forceUpdate();
			},
		}
	};
</script>

<style lang="scss" scoped>
	.lineheight-clear {
		line-height: 1 !important;
	}

	.fs38 {
		font-size: 38rpx !important;
	}

	// 商品列表单列样式
	.goods-list.single-column {

		.goods-item {
			padding: 26rpx;
			background: #fff;
			border-radius: $border-radius;
			display: flex;
			position: relative;
			margin-top: 10rpx;

			&.first-child {
				margin-top: 0;
			}

			.goods-img {
				width: 200rpx;
				height: 200rpx;
				overflow: hidden;
				border-radius: $border-radius;
				margin-right: 20rpx;

				image {
					width: 100%;
					height: 100%;
				}
			}

			.goods-tag {
				color: #fff;
				line-height: 1;
				padding: 8rpx 12rpx;
				position: absolute;
				border-top-left-radius: $border-radius;
				border-bottom-right-radius: $border-radius;
				top: 26rpx;
				left: 26rpx;
				font-size: $font-size-goods-tag;
			}

			.goods-tag-img {
				position: absolute;
				border-top-left-radius: $border-radius;
				width: 80rpx;
				height: 80rpx;
				top: 26rpx;
				left: 26rpx;
				z-index: 5;
				overflow: hidden;

				image {
					width: 100%;
					height: 100%;
				}
			}

			.info-wrap {
				flex: 1;
				display: flex;
				flex-direction: column;
			}

			.name-wrap {
				flex: 1;
			}

			.goods-name {
				font-size: $margin-both;
				line-height: 1.4;
				overflow: hidden;
				text-overflow: ellipsis;
				display: -webkit-box;
				-webkit-line-clamp: 2;
				-webkit-box-orient: vertical;
				height: 80rpx;
			}

			.introduction {
				line-height: 1;
				margin-top: 10rpx;
			}

			.discount-price {
				display: inline-block;
				font-weight: bold;
				line-height: 1;
				margin-top: 16rpx;

				.unit {
					margin-right: 6rpx;
				}
			}

			.pro-info {
				display: flex;
				margin-top: 16rpx;

				.delete-price {
					text-decoration: line-through;
					flex: 1;

					.unit {
						margin-right: 6rpx;
					}
				}

				&>view {
					line-height: 1;

					&:nth-child(2) {
						text-align: right;
					}
				}
			}

			.member-price-tag {
				display: inline-block;
				width: 60rpx;
				line-height: 1;
				margin-left: 6rpx;

				image {
					width: 100%;
				}
			}
		}

	}

	// 商品列表双列样式
	.goods-list.double-column {
		display: flex;
		flex-wrap: wrap;
		// margin: 0 $margin-both;

		.goods-item {
			flex: 1;
			position: relative;
			background-color: #fff;
			flex-basis: 48%;
			max-width: calc((100% - 30rpx) / 2);
			margin-right: $margin-both;
			margin-bottom: $margin-updown;
			border-radius: $border-radius;

			&:nth-child(2n) {
				margin-right: 0;
			}

			.goods-img {
				position: relative;
				overflow: hidden;
				padding-top: 100%;
				border-top-left-radius: $border-radius;
				border-top-right-radius: $border-radius;

				image {
					width: 100%;
					position: absolute;
					top: 50%;
					left: 0;
					transform: translateY(-50%);
				}
			}

			.goods-tag {
				color: #fff;
				line-height: 1;
				padding: 8rpx 16rpx;
				position: absolute;
				border-bottom-right-radius: $border-radius;
				top: 0;
				left: 0;
				font-size: $font-size-goods-tag;
			}

			.goods-tag-img {
				position: absolute;
				border-top-left-radius: $border-radius;
				width: 80rpx;
				height: 80rpx;
				top: 0;
				left: 0;
				z-index: 5;
				overflow: hidden;

				image {
					width: 100%;
					height: 100%;
				}
			}

			.info-wrap {
				padding: 0 26rpx 26rpx 26rpx;
			}

			.goods-name {
				font-size: $margin-both;
				line-height: 1.4;
				overflow: hidden;
				text-overflow: ellipsis;
				display: -webkit-box;
				-webkit-line-clamp: 2;
				-webkit-box-orient: vertical;
				margin-top: 20rpx;
				height: 80rpx;
			}

			.discount-price {
				display: inline-block;
				font-weight: bold;
				line-height: 1;
				margin-top: 16rpx;

				.unit {
					margin-right: 6rpx;
				}
			}

			.pro-info {
				display: flex;
				margin-top: 16rpx;

				.delete-price {
					text-decoration: line-through;
					flex: 1;

					.unit {
						margin-right: 6rpx;
					}
				}

				&>view {
					line-height: 1;

					&:nth-child(2) {
						text-align: right;
					}
				}
			}

			.member-price-tag {
				display: inline-block;
				width: 60rpx;
				line-height: 1;
				margin-left: 6rpx;

				image {
					width: 100%;
				}
			}
		}
	}

	.goods-list-3.single-column {
		margin: 0 -15px;
		background-color: #FFFFFF;
		padding: 0 30rpx;

		.goods-item {
			height: 280rpx;
			padding: 40rpx 0 30rpx;
			border-bottom: 2rpx solid #EEEEEE;

			&:last-child {
				border-bottom: none;
			}
			
			.goods-tag {
				top: 42rpx;
				left: 0;
			}
			
			.name-wrap {
				flex: none;

				.goods-name {
					font-weight: bold;
					height: 84rpx;
					line-height: 42rpx;
					position: relative;
					top: -8rpx;
				}
				
				.goods-label {
					width: 110rpx;
					height: 30rpx;
					background-color: rgba(255, 25, 25, .1);
					font-size: 22rpx;
					line-height: 30rpx;
					color: #FF4544;
					text-align: center;
					margin-bottom: 15rpx;
				}
				
				.goods-sale {
					display: flex;
					align-items: center;
					font-size: 22rpx;
					line-height: 1;
					
					.split {
						width: 1rpx;
						height: 20rpx;
						background-color: $color-tip;
						margin: 0 10rpx;
					}
				}
			}
			
			.goods-img {
				width: 260rpx;
				height: 260rpx;
			}

			.member-price-tag {
				display: block;
				width: 80rpx;
				margin-left: 0;
				position: relative;
				margin-top: 16rpx;
				
				image {
					width: 80rpx;
					height: 37rpx;
				}

				text {
					font-size: 20rpx;
					color: #FFFFFF;
					display: inline-block;
					width: 80rpx;
					height: 32rpx;
					text-align: center;
					line-height: 32rpx;
					position: absolute;
					top: 0;
					left: 0;
				}
			}
			
			.member-price-tag-vip-1 {
				text {
					color: #FFFD8F;
				}
			}

			.discount-price {
				margin-top: 0;
				color: #FF1919;
				line-height: 1;

				.price {
					font-size: 38rpx;
					line-height: 1;
				}
			}

			.pro-info {
				margin-top: 10rpx;
				
				.delete-price {
					font-size: 26rpx;
				}
			}

			.info-wrap {
				justify-content: space-between;
				position: relative;
			}

			.careBox {
				position: absolute;
				bottom: 0;
				right: 0;
				width: 182rpx;
				height: 70rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				
				.careBox-con {
					width: 100%;
					height: 100%;
					position: relative;
				}

				.info-btn {
					width: 182rpx;
					height: 70rpx;
					margin: 0;
					color: #FFFFFF;
					line-height: 70rpx;
					padding: 0;
					font-size: 26rpx;
					border-radius: 35rpx;
				}
				.tag-num {
					display: block;
					width: 40rpx;
					height: 40rpx;
					line-height: 40rpx;
					background: #FF1919;
					text-align: center;
					color: #fff;
					border-radius: 50%;
					position: absolute;
					top: -20rpx;
					right: 20rpx;
					font-size: 24rpx;
				}
			}

			.careBox input {
				font-size: 36rpx;
				width: 60rpx;
				padding: 0 8rpx 4rpx 4rpx;
				box-sizing: border-box;
				text-align: center;
				font-weight: bold;
			}

			.careBox .iconfont {
				font-size: 60rpx;
			}
		}
	}
</style>
